文章目录

The classical and prototypal paradigms for creating new objects are very different from each other, and the objects that each one produces behave differently. Each paradigm has its own pros and cons, which should help you determine which one to use in a given situation.

Classical inheritance is well understood, both in JavaScript and the programmer community in general. Almost all object-oriented code written in JavaScript uses this paradigm. If you are creating an API for widespread use, or if there is the possibility that other programmers not familiar with prototypal inheritance will be working on your code, it is best to go with classical. JavaScript is the only popular, widely used language that uses prototypal inheritance, so odds are most people will never have used it before. It can also be confusing to have an object with links back to its prototype object. Programmers who don’t fully understand prototypal inheritance will think of this as some sort of reverse inheritance, where the parent inherits from its children. Even though this isn’t the case, it can still be a very confusing topic. But since this form of classical inheritance is only imitating true class-based inheritance, advanced JavaScript programmers need to understand how prototypal inheritance truly works at some point anyway. Some would argue that hiding this fact does more harm than good.

Prototypal inheritance is very memory-efficient. Because of the way prototype chain reads members, all cloned objects share a single copy of each attribute and method, until those attributes and methods are written to directly on the cloned object. Contrast this with the objects created using classical inheritance, where each object has a copy of every attribute (and private
method) in memory. The savings here are enormous. It also seems to be a much more
elegant approach, needing only a single clone function, rather than several lines of incomprehensible syntax such as SuperClass.call(this, arg) and SubClass.prototype = new SuperClass for each class you want to extend (it is true, however, that some of these lines can, in turn, be condensed into the extend function). Don’t think that just because prototypal inheritance is simple that it isn’t also complex. Its power lies in its simplicity.

The decision to use classical or prototypal inheritance probably depends most on how well you like each paradigm. Some people seem naturally drawn to the simplicity of prototypal inheritance, while others are much more comfortable in the more familiar classical.

文章目录